package com.bainuo.doctor.common.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewGroup;

import com.bainuo.doctor.common.R;
import com.bainuo.doctor.common.widget.CustomEditText;
import com.bainuo.doctor.common.util.DisplayUtil;


/**
 * Created by faraway on 24/7/17.
 */

public class CountEditText extends CustomEditText {

    private Context context;

    private int maxLen = -1;

    public CountEditText(Context context) {
        super(context);
        init(context);
    }

    public CountEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private int getPx(int dp){
        return DisplayUtil.dip2px(context,dp);
    }

    void init(Context context){
        this.context = context;
        setPadding(getPaddingLeft(),getPaddingTop(),getPaddingRight(),getPaddingBottom()+getPx(20));
//        addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });
    }


    public void setTextLimit(int maxLen){
        if(maxLen >=0 ){
            this.maxLen = maxLen;
            setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLen)});
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (maxLen != -1){
            int len = getText().toString().length();

            Paint textPaint = new Paint();
            textPaint.setStyle(Paint.Style.STROKE);
            textPaint.setAntiAlias(true);
//            textPaint.setARGB(0xFF,0x84,0x84,0x84);
//            textPaint.setColor(getTextColors().getDefaultColor());
            textPaint.setColor(getResources().getColor(R.color.common_font_gray));
            textPaint.setTextSize(getTextSize()*4/5);

            Rect rect = new Rect();

            String txt = len+"/"+maxLen;
            textPaint.getTextBounds(txt,0,txt.length(),rect);
            canvas.drawText(txt,getWidth()-rect.width()-getPx(10),getHeight()-getPx(10),textPaint);
        }

    }


    @Override
    public ViewGroup.LayoutParams getLayoutParams() {
        return super.getLayoutParams();
    }

    @Override
    public float getY() {
        return super.getY();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }
}
